package fr.thelem.gestiondemandesthelem.web.commons;

import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import org.apache.log4j.Logger;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.ldap.userdetails.LdapUserDetailsMapper;

import fr.thelem.gestiondemandesthelem.service.IAppliService;

public class LdapPopulator extends LdapUserDetailsMapper {
    private static final Logger LOGGER = Logger.getLogger(LdapPopulator.class);

    private IAppliService appliService;

    /**
     * Affectation de appliService
     * 
     * @param appliService appliService à affecter
     */
    public void setAppliService(IAppliService appliService) {
        this.appliService = appliService;
    }

    @Override
    public UserDetails mapUserFromContext(DirContextOperations ctx, String username, Collection<GrantedAuthority> authority) {
        UserDetails originalUser = super.mapUserFromContext(ctx, username, authority);

        Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();

        if (appliService.isAdministrateurExiste(originalUser.getUsername())) {
            authorities.add(new GrantedAuthorityImpl("ROLE_ADMIN"));
            authorities.add(new GrantedAuthorityImpl("ROLE_USER"));
            appliService.majAdministrateur(originalUser.getUsername(), new Date());
        } else {
            if (appliService.isUtilisateurExiste(originalUser.getUsername())) {
                authorities.add(new GrantedAuthorityImpl("ROLE_USER"));
                appliService.majUtilisateur(originalUser.getUsername(), new Date());
            } else {
                appliService.ajouterUtilisateur(originalUser.getUsername(), new Date(), new Date());
                authorities.add(new GrantedAuthorityImpl("ROLE_USER"));
            }
        }

        User newUser =
                new User(originalUser.getUsername(), originalUser.getPassword(), originalUser.isEnabled(), originalUser.isAccountNonExpired(), originalUser
                        .isCredentialsNonExpired(), originalUser.isAccountNonLocked(), authorities);
        return newUser;
    }
}
